#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <cerrno>
#include <cstring>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>

namespace udp_server
{
    enum
    {
        SOCKET_ERR = 1,
        BIND_ERR
    };

    const static uint16_t default_port = 8080;

    class UdpServer 
    {
    public:
        UdpServer(std::string ip, uint16_t port = default_port)
            :ip_(ip)
            ,port_(port)
        {
            std::cout << "server addr: " << ip_ << " : " << port_ << std::endl;
        }
        void InitServer()
        {
            sock_ = socket(AF_INET, SOCK_DGRAM, 0);
            if (sock_ < 0)
            {
                std::cout << "create socket error: " << strerror(errno) << std::endl;
                exit(SOCKET_ERR);
            }
            std::cout << "create socket success: " << sock_ << std::endl;
            
            struct sockaddr_in local;
            bzero(&local, 0);
            local.sin_family = AF_INET;
            local.sin_port = htons(port_);
            local.sin_addr.s_addr = inet_addr(ip_.c_str());
            if (bind(sock_, (sockaddr*)&local, sizeof(local)) < 0)
            {
                std::cout << "bind socket error: " << strerror(errno) << std::endl;
                exit(BIND_ERR);
            }
            std::cout << "bind socket success: " << sock_ << std::endl;
        }
        void Start()
        {}
        ~UdpServer()
        {}
    private:
        int sock_;
        uint16_t port_;
        std::string ip_;
    };
}